package com.wanli.storemobile;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.alibaba.idst.token.AccessToken;
import com.alibaba.idst.util.SpeechSynthesizer;
import com.alibaba.idst.util.SpeechSynthesizerCallback;
import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.wanli.storemobile.a_main.MainActivity;
import com.wanli.storemobile.bean.AliPushBean;
import com.wanli.storemobile.login.LoginActivity;
import com.wanli.storemobile.utils.NumberFormatUtils;
import com.wanli.storemobile.utils.SPManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;

import static android.content.Context.KEYGUARD_SERVICE;
import static android.content.Context.NOTIFICATION_SERVICE;

public class AliPushReceiver extends MessageReceiver {

    // 消息接收部分的LOG_TAG
    public static final String REC_TAG = "AliPushReceiver";
    private SpeechSynthesizer speechSynthesizer;
    private static AudioPlayer audioPlayer;

    @Override
    public void onNotification(Context context, String title, String summary, Map<String, String> extraMap) {
        // TODO 处理推送通知
        Log.e(REC_TAG, "Receive notification, title: " + title + ", summary: " + summary + ", extraMap: " + extraMap);
    }

    @Override
    public void onMessage(Context context, CPushMessage cPushMessage) {
        Log.e(REC_TAG, "onMessage, messageId: " + cPushMessage.getMessageId() + ", title: " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent());
        if (!TextUtils.isEmpty(SPManager.getInstance().getToken()) && !TextUtils.isEmpty(SPManager.getInstance().getUserInfoJson())) {
            String moneyStr = "";
            String pay_env = "";
            String contentText = "";
            try {
                JSONObject jsonObject = new JSONObject(cPushMessage.getContent());
                String type = jsonObject.getString("type");
                JSONObject data = jsonObject.getJSONObject("data");
                if ("orderPaid".equals(type)) {
                    moneyStr = NumberFormatUtils.formatDouble(Double.parseDouble(data.get("order_fee").toString()) / 100.0);
                    pay_env = data.get("pay_env").toString();
                    if (pay_env.equals("WXZF")) {
                        contentText = "万丽收银微信收款" + moneyStr + "元";
                    }
                    if (pay_env.equals("ZFBZF")) {
                        contentText = "万丽收银支付宝收款" + moneyStr + "元";
                    }
                    if (pay_env.equals("YSFZF")) {
                        contentText = "万丽收银云闪付收款" + moneyStr + "元";
                    }
                    if (pay_env.equals("")) {
                        contentText = "万丽收银云闪付收款" + moneyStr + "元";
                    }


                    if (!TextUtils.isEmpty(contentText)) {
                        EventBus.getDefault().post(new AliPushBean());
                        processCustomMessage(context, contentText);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("true".equals(SPManager.getInstance().getSpeechSwitch())) {
                if (!TextUtils.isEmpty(contentText)) {
                    startSynthesizer(contentText);
                }
            }
        }
    }

    @Override
    public void onNotificationOpened(Context context, String title, String summary, String extraMap) {
        Log.e(REC_TAG, "onNotificationOpened, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }

    @Override
    protected void onNotificationClickedWithNoAction(Context context, String title, String summary, String extraMap) {
        Log.e(REC_TAG, "onNotificationClickedWithNoAction, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }

    @Override
    protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) {
        Log.e(REC_TAG, "onNotificationReceivedInApp, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap + ", openType:" + openType + ", openActivity:" + openActivity + ", openUrl:" + openUrl);
    }

    @Override
    protected void onNotificationRemoved(Context context, String messageId) {
        Log.e(REC_TAG, "onNotificationRemoved");
    }

    public void startSynthesizer(String content) {
        String speechToken = SPManager.getInstance().getSpeechToken();
        if (TextUtils.isEmpty(speechToken)) {
            refreshSpeechToken(content);
            return;
        }
        long expireTime = Long.parseLong(speechToken.split("_")[1]);
        if (expireTime < System.currentTimeMillis()) {
            refreshSpeechToken(content);
            return;
        }
        String token = speechToken.split("_")[0];
        synchronized (AliPushReceiver.this) {
            try {
                // 第二步，定义语音合成回调类
                MyCallback callback = new MyCallback();
                // 第三步，创建语音合成对象
                speechSynthesizer = MyApplication.getClient().createSynthesizerRequest(callback);
                callback.setSynthesizer(speechSynthesizer);
                audioPlayer = new AudioPlayer();
                // Token有有效期，请使用https://help.aliyun.com/document_detail/72153.html 动态生成token
                speechSynthesizer.setToken(token);
                // 请使用阿里云语音服务管控台(https://nls-portal.console.aliyun.com/)生成您的appkey
                speechSynthesizer.setAppkey("kNrPCE3421BTAmyG");
                // 第五步，设置相关参数，以下选项都会改变最终合成的语音效果，可以按文档调整试听效果
                // 设置要转为语音的文本
                speechSynthesizer.setText(content);
                // 设置语音数据采样率
                speechSynthesizer.setSampleRate(SpeechSynthesizer.SAMPLE_RATE_16K);
                // 设置语音编码，pcm编码可以直接用audioTrack播放，其他编码不行
                speechSynthesizer.setFormat(SpeechSynthesizer.FORMAT_PCM);
                // 第六步，开始合成
                if (speechSynthesizer.start() < 0) {
                    speechSynthesizer.stop();
                    return;
                }
            } catch (Exception e) {

            }
        }
    }

    private static class MyCallback implements SpeechSynthesizerCallback {
        private WeakReference<SpeechSynthesizer> synthesizerWeakReference;

        public void setSynthesizer(SpeechSynthesizer speechSynthesizer) {
            synthesizerWeakReference = new WeakReference<>(speechSynthesizer);
        }

        // 语音合成开始的回调
        @Override
        public void onSynthesisStarted(String msg, int code) {
            Log.d(TAG, "OnSynthesisStarted " + msg + ": " + String.valueOf(code));
        }

        // 第七步，获取音频数据的回调，在这里把音频写入播放器
        @Override
        public void onBinaryReceived(byte[] data, int code) {
            Log.i(TAG, "binary received length: " + data.length);
            if (audioPlayer != null) {
                audioPlayer.setAudioData(data);
            }
        }

        @Override
        public void onMetaInfo(String message, int code) {
            Log.d(TAG, "onMetaInfo " + message + ": " + String.valueOf(code));
        }

        // 语音合成完成的回调，在这里关闭播放器
        @Override
        public void onSynthesisCompleted(final String msg, int code) {
            Log.d(TAG, "OnSynthesisCompleted " + msg + ": " + String.valueOf(code));
            if (synthesizerWeakReference != null && synthesizerWeakReference.get() != null) {
                // 第八步，结束合成
                synthesizerWeakReference.get().stop();
            }

        }

        // 调用失败的回调
        @Override
        public void onTaskFailed(String msg, int code) {
            Log.d(TAG, "OnTaskFailed " + msg + ": " + String.valueOf(code));
            if (synthesizerWeakReference != null && synthesizerWeakReference.get() != null) {
                // 第八步，结束合成
                synthesizerWeakReference.get().stop();
            }
        }

        // 连接关闭的回调
        @Override
        public void onChannelClosed(String msg, int code) {
            Log.d(TAG, "OnChannelClosed " + msg + ": " + String.valueOf(code));
        }
    }

    /**
     * 刷新token
     */
    public void refreshSpeechToken(String content) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AccessToken token = new AccessToken("LTAI5t6kS3cnvPpFSTavLFdd", "RetS4VjHo4YZIrsVMWEh9ooecMiqjK");
                    token.apply();
                    String accessToken = token.getToken();
                    long expireTime = token.getExpireTime() * 1000;
                    SPManager.getInstance().saveSpeechToken(accessToken, expireTime + "");


                    try {
                        // 第二步，定义语音合成回调类
                        MyCallback callback = new MyCallback();
                        // 第三步，创建语音合成对象
                        speechSynthesizer = MyApplication.getClient().createSynthesizerRequest(callback);
                        callback.setSynthesizer(speechSynthesizer);
                        audioPlayer = new AudioPlayer();
                        // Token有有效期，请使用https://help.aliyun.com/document_detail/72153.html 动态生成token
                        speechSynthesizer.setToken(accessToken);
                        // 请使用阿里云语音服务管控台(https://nls-portal.console.aliyun.com/)生成您的appkey
                        speechSynthesizer.setAppkey("kNrPCE3421BTAmyG");
                        // 第五步，设置相关参数，以下选项都会改变最终合成的语音效果，可以按文档调整试听效果
                        // 设置要转为语音的文本
                        speechSynthesizer.setText(content);
                        // 设置语音数据采样率
                        speechSynthesizer.setSampleRate(SpeechSynthesizer.SAMPLE_RATE_16K);
                        // 设置语音编码，pcm编码可以直接用audioTrack播放，其他编码不行
                        speechSynthesizer.setFormat(SpeechSynthesizer.FORMAT_PCM);
                        // 第六步，开始合成
                        if (speechSynthesizer.start() < 0) {
                            speechSynthesizer.stop();
                            return;
                        }
                    } catch (Exception e) {

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 处理自定义通知
     *
     * @param context
     */
    private void processCustomMessage(Context context, String contentText) {
        //显示不重复通知
        int requestCode = (int) System.currentTimeMillis();
        String channelID = "1";
        String channelName = "万丽收银";
        String description = "通知";

        Intent intent = null;
        // 跳转的Activity
        if (!TextUtils.isEmpty(SPManager.getInstance().getToken()) && !TextUtils.isEmpty(SPManager.getInstance().getUserInfoJson())) {
            intent = new Intent(context, MainActivity.class);
        } else {
            intent = new Intent(context, LoginActivity.class);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            return;
        }

        //适配安卓8.0的消息渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context, channelID);

        notification.setAutoCancel(true)//点击后消失
                .setWhen(System.currentTimeMillis())
                .setContentTitle("万丽收银")
                .setContentText(contentText)
                .setDefaults(Notification.DEFAULT_ALL)
                .setVibrate(new long[]{0, 300, 300, 300})
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher);

        notificationManager.notify(requestCode, notification.build());
        if ("true".equals(SPManager.getInstance().getSpeechSwitch())) {
            wakeUpAndUnlock();
        }
    }

    /**
     * 唤醒手机屏幕并解锁
     */
    public static void wakeUpAndUnlock() {
        // 获取电源管理器对象
        PowerManager pm = (PowerManager) MyApplication.getContext()
                .getSystemService(Context.POWER_SERVICE);
        boolean screenOn = pm.isScreenOn();
        if (!screenOn) {
            // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            @SuppressLint("InvalidWakeLockTag")
            PowerManager.WakeLock wl = pm.newWakeLock(
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire(10000); // 点亮屏幕
            wl.release(); // 释放
        }
        // 屏幕解锁
        KeyguardManager keyguardManager = (KeyguardManager) MyApplication.getContext().getSystemService(KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
        // 屏幕锁定
        keyguardLock.reenableKeyguard();
        keyguardLock.disableKeyguard(); // 解锁
    }

}